import { Bootstrap } from "@midwayjs/bootstrap";
import { resolve } from "path";
import { setConfig, setProjectRoot, getConfig } from "@midwayjs/hooks/internal";
import { PROJECT_DIR } from "../node/misc";
import type { ServerOptions, ServerResult } from "./interfaces";
import { getUnOccupiedPort } from "../node/network";
import killPort from "cross-port-killer";

async function start({
  port = 8080,
  root = resolve(PROJECT_DIR, "dist/hooks"),
  portMode,
}: ServerOptions): Promise<ServerResult> {
  const config = {
    ...getConfig(root),
    build: { outDir: "./" },
  };
  setProjectRoot(root);
  setConfig(config);

  if (portMode === "change-when-occupied") {
    port = await getUnOccupiedPort(port);
  }
  if (portMode === "kill-when-occupied") {
    try {
      killPort(port);
    } catch (error) {
      //
    }
  }

  process.env.MIDWAY_HTTP_PORT = port + "";
  const server = Bootstrap.configure({
    baseDir: root,
    ignore: ["**/_client/**"],
  });
  await server.run();
  return { port };
}

export default start;
